package servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
//import org.apache.commons.fileupload.FileItem;

import clienteWeb.ClienteWeb;

import beans.CotizacionBean;

import parser.CotizacionXStream;


public class ProcesarAprobarCotizacion extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	public ProcesarAprobarCotizacion() 
	{
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
		
		if (!isMultipartContent) 
		{
			out.println("No se puede hacer upload<br/>");
			return;
		}

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		try {
				List<FileItem> fields = upload.parseRequest(request);
				Iterator<FileItem> it = fields.iterator();
			
				if (!it.hasNext()) 
				{
					out.println("No se encontraron FIlas");
					return;
				}
			
				while (it.hasNext()) 
				{
					FileItem fileItem = it.next();
				
					boolean isFormField = fileItem.isFormField();
					if (!isFormField) 
					{
						System.out.println(fileItem.getName());
						InputStream uploadedStream = fileItem.getInputStream();
						CotizacionXStream parser = new CotizacionXStream();
			        
						CotizacionBean cotizacionBean  = (CotizacionBean) parser.fromXML(uploadedStream);
						ClienteWeb.getInstancia().aprobarCotizacion(cotizacionBean);
						
						out.println("<html><head>");
						out.println("</head><body>");	
						out.println("<h1>Su cotizacion ha sido aprobada. <a href='index.jsp'>volver</a>"); //chequear
		
					}
				
				}
			
			} 
			catch (FileUploadException e)
			{
				e.printStackTrace();
			}
	}
	
}
